package top.lingkang.potatoserver.config.exception;

import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Component;
import top.lingkang.error.FinalExceptionHandler;
import top.lingkang.error.FinalNotLoginException;
import top.lingkang.error.FinalPermissionException;
import top.lingkang.error.FinalTokenException;
import top.lingkang.potatoserver.constants.HttpConstants;
import top.lingkang.potatoserver.dto.ResponseResult;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author lingkang
 * @date 2021/9/19 0:30
 * @description 自定义异常处理
 */
@Component
public class FinalSecurityExceptionHandler implements FinalExceptionHandler {

    @Override
    public void notLoginException(FinalNotLoginException e, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        httpServletResponse.setHeader("Content-type", "application/json; charset=utf-8");
        httpServletResponse.getWriter().println(JSON.toJSON(new ResponseResult(HttpConstants.AUTH_FAIL, e.getMessage())));
    }

    @Override
    public void tokenException(FinalTokenException e, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        httpServletResponse.setHeader("Content-type", "application/json; charset=utf-8");
        httpServletResponse.getWriter().println(JSON.toJSON(new ResponseResult(HttpConstants.AUTH_FAIL, e.getMessage())));
    }

    @Override
    public void permissionException(FinalPermissionException e, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        httpServletResponse.setHeader("Content-type", "application/json; charset=utf-8");
        httpServletResponse.getWriter().println(JSON.toJSON(new ResponseResult(HttpConstants.AUTH_FAIL, e.getMessage())));
    }
}
